from flask import Blueprint, request, jsonify
from db import Dd
import json
from jwttoken import Myjwt
from tool import RedisCon,RBAC
bp_user = Blueprint('bp_user', __name__)
def get_data():
    data = request.data
    if data:
        data = json.loads(data)
    else:
        data = request.form
    return data


@bp_user.route('/work')
def work():
    db = Dd()
    sql = "select * from workflow"
    res = db.get_all(sql)
    print(res)
    return jsonify({'code': 200, 'list': res})


@bp_user.route('/getdataresource', methods=['GET', 'POST'])
def getdataresource():
    if request.method == 'GET':
        # 从redis取,如果有直接返回
        r = RedisCon()
        values = r.str_get('dataresource')
        if values:
            list1 = eval(values)
        else:
            # 如果没有就查询
            sql = 'select * from data_dource'
            db = Dd()
            res = db.get_all(sql)
            list1 = []
            if res:
                for i in res:
                    dict1 = {'id': i['id'], 'name': i['name']}
                    sql1 = 'select id,name,type from %s' % (i['tablename'])
                    subers = db.get_all(sql1)
                    dict1['mes'] = subers
                    list1.append(dict1)
            # redis存
            r.str_set('dataresource', json.dumps(list1))
        return jsonify({'code': 200, 'list': list1})
    else:
        data = get_data()
        sql = "update workflow set params='%s' where id=%d" % (data['mes'], int(data['id']))
        db = Dd()
        db.update(sql)
        return jsonify({'code': 200})






@bp_user.route('/get_workf',methods=['GET'])
def get_worf():
    id=request.args.get('id')
    db=Dd()
    list=[]
    res=db.get_all('select * from workflow where id=%s' % id)
    print(res)
    for  i  in  res:
        list=i['params']
    print(list)
    return {'code':'200','list':res,'dict':list}


# 提交任务表
# @bp_user.route('/post_task', methods=['POST'])
# def post_task():
#     values = request.form.keys()
#     name = request.form.get('values[姓名]')
#     time = request.form.get('values[开始时间]')
#     type_name = request.form.get('values[文件]')
#     end_time = request.form.get('values[结束时间]')
#     li_you = request.form.get('values[请假理由]')
#     sta_value = request.form.get('values[请假类型]')
#     title=name+sta_value
#     params=[{'姓名':name,'请假类型':sta_value,'开始时间':time,'文件':type_name,'结束时间':end_time,'请假理由':li_you}]
#     db=Dd()
#     db.insert('insert into `task` (title,params) values ("%s","%s")' % (title,params))


#     return {'code': '200'}



def getdeptdata(data):
    db=Dd()
    tree = {}
    list=[]
    for i in data:
        tree[i['id']] = i
    for j in data:
        
        pid = j['orgenid']
        if not pid:
            j['type']=1
            list.append(j)
        else:
            if 'children' not in tree[pid]:
                tree[pid]['children']=[]
            #查询此部门下所有员工
            sql = "select * from user where level=%d"%(j['id'])
            res = db.get_all(sql)
            userlist=[]
            if res:
                for u in res:
                    u['type'] = 3
                    userlist.append(u)
            j['children'] = userlist
            j['type']=2
            tree[pid]['children'].append(j)

    return list

@bp_user.route('/getcomanyuser')
def getcomanyuser():
    #获取所有公司及所有部门
    db=Dd()
    sql = "select * from node"
    res = db.get_all(sql)
    print(res,000000000000000000000000)
    mes = getdeptdata(res)
    print(mes,222222222222222222222222)
    return jsonify({'code':200,'list':mes})
    #数据重组，查询员工
@bp_user.route('/taskm',methods=['POST'])
def taskm():
    data = get_data()
    db=Dd()
    r = RedisCon()
    title = data['title']
    params = data['params']
    auditids = data['auditids']
    #添加任务
    sql = "insert into task(title,params,next_audit,status,nexta) values('%s','%s','%s',1,%d)"%(title,params,auditids,auditids[0])
    db.update(sql)
 
    sql1 = "select id,title from task where title='%s'"%(title)
    task = db.find(sql1)
    #把当前任务加到redis中，选用hash类型
    key='task%d'%(auditids[0])
    r.insert_hash(key,task['id'],task['title'])
    return jsonify({"code":200})
